package util

import (
	"fmt"
	"math/rand"
	"net/smtp"
	"server-go/rpc/reward/internal/svc"
	"time"
)

// 利用邮箱发送验证码
func SendCodeEmail(toEmail string, svcCtx *svc.ServiceContext) (err error) {
	c := svcCtx.Config
	em := svcCtx.MyMail
	em.To = []string{toEmail}
	em.Subject = "任务悬赏系统验证码"
	// 随机数
	randomCode := RandCode(6)
	bodyStr := fmt.Sprintf("【任务悬赏系统发送】\n您的验证码是: '%v' , \n验证码将会在5分钟后失效, 请尽快输入", randomCode)
	// 发送
	em.Text = []byte(bodyStr)
	err = em.Send(c.MyMail.MailAddress+":25", smtp.PlainAuth("", c.MyMail.MailNum, c.MyMail.MailCode, c.MyMail.MailAddress))
	if err != nil {
		return err
	}
	// 存入redis
	if err = RedisSet(svcCtx.Redis, toEmail, randomCode, 300); err != nil {
		return err
	}
	return nil
}

// 生成随机数, 可控制几位
func RandCode(num int) string {
	str := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < num; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}
